import multiprocessing
import serial
from serial.serialutil import STOPBITS_ONE
from serial.tools.list_ports import comports
import threading
from queue import Queue

class SerialManage():
    # process_function (传入参数为data，每次读取到数据都会调用该函数)
    def __init__(self,port='COM16',baudrate=115200,bytesize=8,
                    parity='N',stopbits=STOPBITS_ONE):
        self.port = port
        self.baudrate = baudrate
        self.bytesize = bytesize
        self.parity = parity
        self.stopbits = stopbits

        self.ser = None
        self.read_flag = False
        self.read_thread = None
        self.read_queue = Queue()

    def connect_serial(self):
        # 初始化串口
        self.ser = serial.Serial(port=self.port, baudrate= self.baudrate, bytesize= self.bytesize, parity=self.parity, stopbits=self.stopbits)

        # 启动串口读取线程
        self.read_flag = True
        self.read_thread = threading.Thread(target=self.serial_read_thread)
        self.read_thread.daemon = True
        self.read_thread.start()

    # 串口读取线程
    def serial_read_thread(self):
        while self.read_flag:
            if self.ser.in_waiting > 0:
                data = self.ser.read(6)  # 一次性读取全部数据
                self.read_queue.put(data.hex())

    @property
    def isOpen(self):
        return self.ser.isOpen()

    @staticmethod
    def cat_com_list():
        ports = []
        for port in serial.tools.list_ports.comports():
            ports.append(port.name)
        return ports

    def write(self, data:bytearray):
        if self.ser.isOpen():
            self.ser.reset_input_buffer()
            self.ser.write(data)

    def close_serial(self):
        self.read_flag = False
        self.ser.close()


if __name__ == '__main__':
    from time import sleep
    serial_com = SerialManage(port='COM10', baudrate=115200, bytesize=8, parity='N', stopbits=STOPBITS_ONE)
    serial_com.connect_serial()
    sleep(1)
    #print(serial_com.isOpen())
    print(serial_com.cat_com_list())
    serial_com.write(bytearray([0x55,0x00,0x02,0x00,0x00,0x57]))
    sleep(1)
    print(serial_com.read_queue.qsize())
    while serial_com.read_queue.qsize() > 0:
        print(serial_com.read_queue.get())
    while True:
        sleep(100)
        pass
    # serial_com.close_serial()